﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using AsPlugInManager;
using AsLib;

namespace NNLInterface
{
    public partial class frmScheduleZ1 : NNLInterface.frmBaseBasic
    {

        #region 初始化

        string strSQLHead1 = " select  vsz.*,aa.ManCount from vie_Schedule"; //Z1DD

        // 2012-01-12对于制2课，数据量大，所以去掉了对于前工序工程名称的读取
        string strSQLHead2 = " select  vsz.*,aa.ManCount from vie_ScheduleZ2DD ";  

        string strTranNo = "";
        string strGroupNo = "";
        string DeptNo = "";
        string resCode = "";
        string strStartTime = "";
        string strEndTime = "";

        //报表数据源
        DataTable dtReport;

        //报表类型，制1，2，3或5，用1和2代表
        int reporttype = 0;  


        public frmScheduleZ1()
        {
            InitializeComponent();
        }


        public frmScheduleZ1(IASPArgList argList, int reportType)  //记录报表类型1,为1，2，3课报表，2为制5课报表
        {
            InitializeComponent();
            reporttype = reportType;
            this.ImportButtonVisibility = false;
            this.PrintButtonVisibility = true;
            this.lokDepart.EditValueChanged += new EventHandler(lokDepart_EditValueChanged);
            this.lokDepart.ProcessNewValue += new DevExpress.XtraEditors.Controls.ProcessNewValueEventHandler(lokDepart_ProcessNewValue);
        }

        void frmScheduleZ1_Load(object sender, EventArgs e)
        {
            //如果当前工程下的用户名为空，则提示输入
            if (common._userid == "")
            {
                frmLogon frmLog = new frmLogon();
                frmLog.ShowDialog();

                if (frmLog.DialogResult == DialogResult.OK)
                {
                    frmLog.Dispose();
                    frmLog = null;
                }
                else
                {
                    this.Close();
                    return;
                }

            }
            IniDataSource();
        }


        private void IniDataSource()
        {
            this.txtUser.Text = common._userid;
            this.txtUserName.Text = common._username;
            this.txtDeptNo.Text = common._DeptNo;
            this.txtDeptName.Text = common._DeptName;

            lokPlanNo.Properties.ShowDropDown = DevExpress.XtraEditors.Controls.ShowDropDown.Never;
            lokDepart.Properties.ShowDropDown = DevExpress.XtraEditors.Controls.ShowDropDown.Never;


            //设定部门的数据源
            SetDeptDataSource();
            string strSQL = strSQLHead1 + common._userid + "DD vsz " 
                             + " LEFT OUTER JOIN (SELECT * FROM ManCount mc WHERE 1=2) aa "
                             + " ON vsz.ItemCode=aa.ItemCode AND vsz.OperationMainResCode=aa.RrsourceCode "
                             + " where 1=2";
            common.SubShowList(accessdb.GetRecord(strSQL).ADODataRst, this.ListGrid, this.ListView, false);
            common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);

            //设定组别的数据源
            SetGroupDataSource();

            //设定资源的数据源
            SetResourceDataSource();


            //初始化日期
            string strDepartNo = common.pro.GetAsStr((TPropertyID)Convert.ToInt32(common.GetLanguageWord("PropertyID", "ProjectUser_DepartNo")), 1);

            //设定版本号
            strSQL =string.Format( "SELECT DISTINCT o.TranNo FROM Operation" + common._userid + " o where o.tranno like '{0}%' ORDER BY o.TranNo desc",strDepartNo);
            DataTable dt=accessdb.GetRecord(strSQL).ADODataRst;
            this.lokPlanNo.Properties.DataSource =dt; 
            if (dt.Rows.Count>=1)
            {
                this.lokPlanNo.Text = dt.Rows[0][0].ToString();
                this.lokPlanNo.EditValue = dt.Rows[0][0].ToString();
            }

            
            common.GetResourceString(this, this.Name+ reporttype.ToString());
            common.RestoreFormLayOut(this.Name+ reporttype, this.layOut, this.grpHead);
            common.ReStoreLayOut(this.ListView, this.Name + reporttype.ToString() + common._userid);

            if (this.reporttype == 1)
                this.Text = common.GetLanguageWord("frmScheduleZ11","frmname");
            else
                this.Text = common.GetLanguageWord("frmScheduleZ12", "frmname");


        }
        #endregion

 

        #region 控件变化事件


        private void SetDeptDataSource()
        {
            //如果是制5课计划，则部门直接是制5课的
            string strSQL = "SELECT DepartNo,DeptName FROM vie_SysUserDepartMent vsudm WHERE vsudm.UserId='" + this.txtUser.Text + "'";
            if (reporttype == 2)
                strSQL += " and   DepartNo like '%5%'";
            else
                strSQL += " and   DepartNo not like '%5%'";

            this.lokDepart.Properties.DataSource = accessdb.GetRecord(strSQL).ADODataRst;
            


        }

        private void SetGroupDataSource()
        {
           //通过组别分类来标识是否属于生产的组别
            string strSQL = "SELECT DISTINCT r.code  as GroupCode FROM Resource" + common._userid + " r WHERE r.RecName='组别分类'";
            this.lokGroup.Properties.DataSource = accessdb.GetRecord(strSQL).ADODataRst;
           


        }


        private void SetResourceDataSource()
        {
            //通过组别分类来标识是否属于生产的机台
            string strSQL = "SELECT r.Code   ResourceCode FROM Resource" + common._userid + " r ";
                          //+ " WHERE r.Code NOT IN (SELECT r2.GroupCode FROM Resource r2) "
                          //+ " AND r.RecType='M' ";
            this.lokRes.Properties.DataSource = accessdb.GetRecord(strSQL).ADODataRst;
            //this.lokRes.EditValue = null;
            //this.lokRes.Text = "";
            if (reporttype == 2)
            {
                if (((DataTable)lokDepart.Properties.DataSource).Rows.Count >= 1)
                {
                    lokDepart.Text = ((DataTable)lokDepart.Properties.DataSource).Rows[0][0].ToString();
                    lokDepart.EditValue = ((DataTable)lokDepart.Properties.DataSource).Rows[0][0].ToString();
                    lokDepart.Properties.ReadOnly = true;
                }
            }

        }

        void lokDepart_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
           lookupeditProcess.LookUpEditProcessNewValue(sender, ref e);
            
        }

        void lokDepart_EditValueChanged(object sender, EventArgs e)
        {
            if (this.lokDepart.Text != "")
                this.txtDepartName.Text = this.lokDepart.GetColumnValue("DeptName").ToString();
            else
                this.txtDepartName.Text = "";
        }

        private void lokDepart_TextChanged(object sender, EventArgs e)
        {
            if (this.lokDepart.Text != "")
                this.txtDepartName.Text = this.lokDepart.GetColumnValue("DeptName").ToString();
            else
                this.txtDepartName.Text = "";
        }
        #endregion

        #region 工具栏按钮事件

        private void frmScheduleZ1_ToolButtonClick(object sender, string e)
        {
            try
            {
                switch (e)
                {
                    case "search":
                        if (!CheckData()) return;
                        if(!GetReportData()) return;
                        strTranNo = this.lokPlanNo.Text;
                        DeptNo = this.lokDepart.Text;
                        strGroupNo = this.lokGroup.Text;
                        strStartTime = this.dteFrom.Text;
                        strEndTime = this.dteTo.Text;
                        resCode = lokRes.Text;
                        common.SubShowList(SearchData(), this.ListGrid, this.ListView, false);
                        common.subIniGrid(this.ListView, common.enumGridStyle.ViewStyle);
                        common.ReStoreLayOut(this.ListView);
                        break;

                    case "excel":
                        subExportXLS();
                        break;

                    case "print":
                        subPrintReport();
                        break;
                    case "exit":
                        common.SaveFormLayOut(this.Name + reporttype , this.layOut, this.grpHead);
                        common.SaveLayout(this.ListView, this.Name + reporttype.ToString()+ common._userid);
                        this.Dispose();
                        break;
                    default:
                        {
                            break;
                        }
                }


            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }


        private void subPrintReport()
        {
            DataTable dtSel = ((DataView)ListView.DataSource).Table;
            if (dtSel.Rows.Count <= 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("没有数据可供打印!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;

            }

            //判断报表的类型，是否是制1，2，3或制5课
            DevExpress.XtraReports.UI.XtraReport report=new DevExpress.XtraReports.UI.XtraReport();
            report.PrintingSystem.ShowMarginsWarning = false;

            switch (this.reporttype )
            {
                case 1:         //制1，2，3
                    report = new rptScheduleZ1();
                    report.Parameters["totalman"].Value = (this.calOld.Value + this.calNew.Value).ToString();
                    report.Parameters["totalnew"].Value = this.calNew.Value.ToString();
                    report.Parameters["totalold"].Value = this.calOld.Value.ToString();
                    report.Parameters["title"].Value = common.sysParameter.ReportTitleZ1;

                    break;
                case 2:
                   report = new rptScheduleZ5();
                   report.Parameters["title"].Value = common.sysParameter.ReportTitleZ5;

                    break;
                
            }

            //报表相关参数设定
            report.Parameters["username"].Value = common._username;
           
            //报表显示
            ReportShow.ShowReport(report, true, dtReport);
          
        }


        private bool CheckData()
        {
            if (this.lokPlanNo.Text == "")
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("生产计划版本号不能为空，请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.lokPlanNo.Focus();
                return false;
            }


            //if (this.lokDepart.Text == "" && reporttype==1)  //如果是制1,2,3的,需要检测课别
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("最终部门不能为空，请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    this.lokDepart.Focus();
            //    return false;
            //}


            //if (this.lokGroup.Text == "" && reporttype == 2)  //如果是制5的,需要检测课别
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("组别编号不能为空，请检查!", common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    this.lokGroup.Focus();
            //    return false;
            //}



            return true;
        }

        private bool GetReportData()
        {
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            try
            {
               //根据版本号生成数据，如果已经生成，则不需要重复生成
                string itemID = Convert.ToString( accessdb.GetField("SELECT CONVERT(VARCHAR(300),GETDATE(),121)"));
                string strUpDate = " SET XACT_ABORT ON  BEGIN TRAN \r\n";
                string strTranNo=this.lokPlanNo.Text;
                string strSQL = "SELECT COUNT(*) FROM Schedule" + common._userid + "D od WHERE od.TranNo='" + strTranNo + "'";
                DataTable OperationDays;

                if (Convert.ToInt32( accessdb.GetField(strSQL))<1)
                {

                    strSQL = "SELECT * FROM vie_OperationDetail" + common._userid + " vod WHERE vod.TranNo='" + strTranNo + "'";
                    DataTable dt=accessdb.GetRecord(strSQL).ADODataRst;


                    //生成每天的工作计划
                    for (int i = 0; i < dt.Rows.Count; i++)   //对应每一个工作
                    {
                        string TimeArray = dt.Rows[i]["TimeArray"].ToString();
                        string OperationNo = dt.Rows[i]["Code"].ToString();
                        string TranNo = dt.Rows[i]["TranNo"].ToString();
                        string TaskType = dt.Rows[i]["TaskType"].ToString();

                        //先找出当前工作所对应的工作日
                        OperationDays = GetOperationDays(TimeArray);

                       

                        for (int j = 1; j <=OperationDays.Rows.Count; j+=2)
                        {
                            //写入每个工作所对应的所有时序,可能存在跨天的情况，需要在显示报表时，对时间段进行分割
                            strUpDate += " INSERT INTO OperationDetailTmp" + common._userid 
                            + "(Code,TranNo,StartTime,EndTime,TaskType,ItemID) VALUES('"
                            +  OperationNo + "','"
                            + TranNo + "','"
                            + OperationDays.Rows[j-1][0].ToString() + "','"
                            + OperationDays.Rows[j][0].ToString() + "','"
                            + TaskType + "','"
                            + itemID + "') \r\n";

                        }

                    }


                    //如果是多芯的数据，则需要将前设置时间变为一芯的设定时间，将制造时间提前处理
                    strUpDate += " EXEC pro_UpdateOperationSeupTime" + common._userid + " '" + strTranNo + "'\r\n";


                    //取得当前的临界时间
                    string dayStartTime = common.pro.DayStartTime.ToString("HH:mm:ss");

                    //分隔时间段
                    strUpDate += " EXEC pro_SplictTimes" + common._userid 
                                + " @ItemID ='" + itemID 
                                + "', @DaySplict ='" + dayStartTime 
                                + "',@EntUser ='" + this.txtUser.Text + "'\n";

                    //2012-02-21根据要生成的数据
                    strUpDate += " EXEC pro_CreatePlanData" + common._userid
                                + "  @tranNo ='" + strTranNo + "'";
                    strUpDate += " commit tran ";
                    accessdb.RsChange(strUpDate);

                }

                return true;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);

                return false;
            }
            finally
            {
                Cursor.Current = currentCursor;
            }
        }


        //找出工作对应的工作日
        private DataTable GetOperationDays(string strTimeArray)
        {
            string[] strTimes;

            DataTable dt = new DataTable("dataTmp");
            dt.Columns.Add("day", typeof(string));    

            strTimes = strTimeArray.Split(';');
            for (int i = 0; i < strTimes.Length; i++)
            {
                dt.Rows.Add(new object[] { strTimes[i].ToString() });
    
            }



            return dt;
        }

        private void subPrint()
        {
            if (!common.CheckExistsData(this.ListView)) return;
            common.PrintView(this.ListGrid, "计划数据");
        }

        private void subExportXLS()
        {
            try
            {
                if (!common.CheckExistsData(this.ListView)) return;
                common.ExportExcel(this.ListView);
                return;
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, common.sysParameter.MessageInf, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private DataTable SearchData()
        {
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            string strSQL="";
            string strCondition="   where TranNo='" + this.lokPlanNo.Text + "'";

            //2012-05-07需要在计划查询中体现出半成品的切换次数
            //取得唯一标识
            string itemID = accessdb.GetField("select CONVERT(NVARCHAR(30),GETDATE(),121)").ToString();

            //取得日境界时间
            string dayStartTime = common.pro.DayStartTime.ToString("HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
            int hour = Convert.ToInt32(dayStartTime.Substring(0, 2));
            int minute = Convert.ToInt32(dayStartTime.Substring(3, 2));
            int second = Convert.ToInt16(dayStartTime.Substring(6, 2));
            strSQL = "EXEC pro_ProductManCount" + common._userid
                         + " '','','"
                         + dayStartTime.ToString() + "',"
                         + hour.ToString() + ","
                         + minute.ToString() + ","
                         + second.ToString() + ",'"
                         + itemID + "','"
                         + this.lokPlanNo.Text + "'";
            if (!accessdb.RsChange(strSQL)) return null;

            //根据选择的条件进行报表显示
            if(this.lokDepart.Text.ToUpper()!="Z2")
                strSQL = strSQLHead1 + common._userid +"DD  vsz" 
                       //需要关联半成品的切换次数
                       + " LEFT OUTER JOIN (SELECT * FROM ManCount mc WHERE mc.ItemID='" + itemID + "') aa "
                       + " ON vsz.ItemCode=aa.ItemCode AND vsz.OperationMainResCode=aa.RrsourceCode "
                       + strCondition;
                    
            else
                strSQL = strSQLHead2 + " vsz "
                       //需要关联半成品的切换次数
                       + " LEFT OUTER JOIN (SELECT * FROM ManCount mc WHERE mc.ItemID='" + itemID + "') aa "
                       + " ON vsz.ItemCode=aa.ItemCode AND vsz.OperationMainResCode=aa.RrsourceCode "
                       + strCondition;

            //通过部门编号的最后一位确定最终部门的范围
            //if (DeptNo != "")
            //{
            //    string strPDep = DeptNo;
            //    strPDep = strPDep.Substring(strPDep.Length - 1, 1);

            //    strSQL += " and  (SUBSTRING( departMent,2,1)='" + strPDep + "' OR SUBSTRING(departMent,4,1)='" + strPDep + "')";
            //}

            if (strGroupNo != "")
            {
                strSQL += " and  GroupCode='" + strGroupNo + "'";

            }

            if (resCode != "")
            {
                strSQL += " and  OperationMainResCode='" + resCode + "'";

            }


            if (strStartTime != "")
            {
                strSQL += " and  PlanDate>='" + strStartTime + "'";

            }

            if (strEndTime != "")
            {
                strSQL += " and  PlanDate<='" + strEndTime + "'";

            }

            strTranNo=this.lokPlanNo.Text;
            dtReport = accessdb.GetRecord(strSQL).ADODataRst;
            Cursor.Current = currentCursor;
 
            return dtReport;
        }



        #endregion

        //切换用户
        private void txtChange_Click(object sender, EventArgs e)
        {
            frmLogon frmLog = new frmLogon();
            frmLog.ShowDialog();

            if (frmLog.DialogResult == DialogResult.OK)
            {
                IniDataSource();
            }
           
            frmLog.Dispose();
            frmLog = null;

        }

        private void frmScheduleZ1_FormClosing(object sender, FormClosingEventArgs e)
        {
            serial.SerializeBinary(common.sysParameter, Application.StartupPath + @"\NNLInterface.dat");
            common._its_accessdb = null;
            common.pro = null;
            GC.Collect();
        }

    }
}
